var express = require('express');
var router = express.Router();
var goodModel = require('../models/goodModel')
//管理系统设置的权限
var { verifytoken } = require('../utils/jwt')

router.get('/list', function(req, res) {
    console.log('req headers', req.headers)
  let { page,size,name,cate,start_time,end_time,min_price,max_price } = req.query
  //用于查询的入参，几乎都是非必填
  page = parseInt(page || 1)
  size = parseInt(size || 10)

  const params = {
    name: new RegExp(name, 'img')
  }

  verifytoken(req, res).then(user=>{
      if(user&&user._id) {
        goodModel.find(params)
        .limit(size)
        .skip((page-1)*size)
        .sort({creat_time:-1})
        .then(list=>{
          goodModel.find(params).count().then(total=>{
            res.json({err:0,msg:'success',data:{list, total}})
          })
        })
      }
  })
});

router.post('/add/or/edit', (req, res)=>{
  const { id, name, desc, price, img, hot, cate,creat_time } = req.body
  //参数校验
  const ele = {
    name,
    desc,
    price,
    img,
    hot,
    cate,
    creat_time
  }
  if(id) {
    goodModel.updateOne({_id: id}, {$set: ele}).then(doc=>{
      res.json({err:0, msg:'success', data:{info:doc}})
    })
  } else {
    goodModel.insertMany([ele]).then(doc=>{
      res.json({err:0, msg:'success', data:{info:doc}})
    })
  }
})

router.get('/info', (req, res)=>{
  const { id } = req.query
  goodModel.findOne({_id:id}).then(doc=>{
    res.json({err:0, msg:'success', data:{info:doc}})
  })
})

module.exports = router;